// services/category.go
package services

import (
	"context"
	"errors"
	"zwai-app/db"
	"zwai-app/models"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

var ErrCategoryNotFound = errors.New("category not found")

func CreateCategory(ctx context.Context, name string) (primitive.ObjectID, error) {
	coll := db.Client.Database(db.DBName).Collection("Category")
	res, err := coll.InsertOne(ctx, models.Category{Name: name})
	if err != nil {
		return primitive.NilObjectID, err
	}
	return res.InsertedID.(primitive.ObjectID), nil
}

func GetCategories(ctx context.Context) ([]models.Category, error) {
	coll := db.Client.Database(db.DBName).Collection("Category")
	cursor, err := coll.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)
	var out []models.Category
	for cursor.Next(ctx) {
		var c models.Category
		if err := cursor.Decode(&c); err == nil {
			out = append(out, c)
		}
	}
	return out, nil
}

func UpdateCategory(ctx context.Context, id primitive.ObjectID, name string) error {
	coll := db.Client.Database(db.DBName).Collection("Category")
	res, err := coll.UpdateOne(ctx, bson.M{"_id": id}, bson.M{"$set": bson.M{"name": name}})
	if err != nil {
		return err
	}
	if res.MatchedCount == 0 {
		return ErrCategoryNotFound
	}
	return nil
}

func DeleteCategory(ctx context.Context, id primitive.ObjectID) error {
	coll := db.Client.Database(db.DBName).Collection("Category")
	res, err := coll.DeleteOne(ctx, bson.M{"_id": id})
	if err != nil {
		return err
	}
	if res.DeletedCount == 0 {
		return ErrCategoryNotFound
	}
	return nil
}
